package org.jeecg.modules.job;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.common.FocRequest;
import org.jeecg.modules.foc.FocController;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * foc每两秒发送一次心跳检查
 */
@Component
@Slf4j
public class EmsHeadJob implements Job {
    @Value("${ems.url}")
    public String emsUrl;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private FocController focController;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Map<String, Object> parm = new HashMap<>();
        FocRequest focRequest = new FocRequest();
        parm.put("heartbeat_time", System.currentTimeMillis());
        //开始进行心跳检查
        focRequest.setData(parm);
        log.debug("心跳检查请求路径以及参数：{}", focRequest);
        try {
            HttpResponse execute = HttpUtil.createPost(emsUrl + "/north/heartbeat").header("token", redisUtil.get("token").toString()).body(JSONObject.toJSONString(focRequest)).execute();
            String heartbeatTime = execute.body();
            log.debug("心跳检查返回信息：{}", heartbeatTime);
            JSONObject jsonObject = JSON.parseObject(heartbeatTime);
            jsonObject = jsonObject.getJSONObject("data");
            Long heartbeatTime1 = jsonObject.getLong("heartbeat_time");
            //todo 该时间与系统差值超过1秒，则登出
            if (System.currentTimeMillis() - heartbeatTime1 > 1000) {
                // log.info("心跳检查超时，登出");
            }
        } catch (Exception e) {
            log.error("心跳检查超时，登出");
            focController.login();
            e.printStackTrace();

        }


    }
}
